package com.example.springkotlin.util

import org.springframework.util.FileCopyUtils
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.http.HttpServletRequest

open class FileUtil {
    companion object{
        fun upload(mFile: MultipartFile, request: HttpServletRequest?): String {
            val yformat = SimpleDateFormat("yyyy")
            val mformat = SimpleDateFormat("MM")
            val dformat = SimpleDateFormat("dd")
            val nowTime = Date()
            val year = yformat.format(nowTime)
            val month = mformat.format(nowTime)
            val day = dformat.format(nowTime)
            val SavePath = request?.getSession()?.getServletContext()?.getRealPath(
                "/"
            ) + File.separator + "files/" + year + "_" + month + "_" + day + "/";
            val directory = File(SavePath)
            if (!directory.exists()) {
                directory.mkdirs()
            }
            val SaveUrl = "/files/" + year + "_" + month + "_" + day + "/"
//            val dt = Date().time.toInt()
//            val random = Random().nextInt()
//            println("dt: $dt ,, random: $random")
//            //文件重新命名
//            val objectarray = intArrayOf(dt, random)
//            objectarray.forEach(::println)
//            val FileNameAuto = String.format(
//                "%X_%X", objectarray
//            )
            var uuid:String = UUID.randomUUID().toString()
            val name = mFile.getOriginalFilename()
            val pos = name!!.lastIndexOf(".")
            //获取文件名后缀Fi
            val ext = name!!.substring(pos)
            var baseName:String = uuid + ext
            var outputStream: OutputStream? = null
            var path: String = SavePath + baseName;
            try {
                outputStream = FileOutputStream(path)
                FileCopyUtils.copy(mFile.getInputStream(), outputStream);
            } catch (e: Exception) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (e: IOException) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return SaveUrl + baseName;
        }

        //删除
        fun deleteFile (request: HttpServletRequest?, filename: String?) {
            val f = request?.getSession()?.getServletContext()?.getRealPath(
                "/"
            ) + filename;
            val file = File(f);
            file.delete();
        }
    }

}
